<template>
  <div id="doctorDetail">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <a-space direction="vertical" style="width: 100%">
      <!-- 消息詳情卡片 -->
      <a-card title="醫師詳情" :loading="loading1">
        <template v-if="!loading1 && !doctorDetail.id">
          <a-empty description="數據加載失敗，請重試" />
        </template>
        <template v-else>
          <a-descriptions bordered>
            <a-descriptions-item label="醫師姓名">
              {{ doctorDetail.name }}
            </a-descriptions-item>
            <a-descriptions-item label="員工編號">
              {{ doctorDetail.staffCode }}
            </a-descriptions-item>
            <a-descriptions-item label="員工類型">
              <a-tag :color="doctorDetail.staffType === 2 ? 'blue' : 'green'">
                {{ doctorDetail.staffType === 2 ? "員工" : "合作" }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="當前駐診形式">
              <a-tag
                :color="doctorDetail.currentShift === 1 ? '#2db7f5' : '#88e8db'"
              >
                {{ doctorDetail.currentShift === 1 ? "全日" : "半日" }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="POS服務編碼">
              {{ doctorDetail.productCode }}
            </a-descriptions-item>

            <a-descriptions-item label="狀態">
              <a-tag :color="!doctorDetail.lastDate ? 'processing' : 'error'">
                {{ !doctorDetail.lastDate ? "在職" : "離職" }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="創建時間">{{
              $formatDate(doctorDetail.createdAt)
            }}</a-descriptions-item>
            <a-descriptions-item label="更新時間">{{
              $formatDate(doctorDetail.updatedAt)
            }}</a-descriptions-item>
          </a-descriptions>
        </template>
      </a-card>

      <a-card title="醫師權益" :loading="loading1">
        <a-row :gutter="[50, 18]">
          <a-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="6"
            v-for="item in rightArr"
            :key="item.key"
          >
            <a-badge-ribbon :color="item.can ? 'green' : 'red'">
              <template #text>
                {{ item.can ? "允許" : "禁止" }}
              </template>
              <a-card bordered hoverable
                ><a-typography-title :level="5">{{
                  item.lable
                }}</a-typography-title></a-card
              >
            </a-badge-ribbon>
          </a-col>
        </a-row>
      </a-card>

      <!-- 駐診形式記錄列表 -->
      <a-card :bordered="false" title="駐診形式記錄" class="data-card">
        <template #extra>
          <a-button
            type="primary"
            size="small"
            shape="round"
            @click="handleCreate"
          >
            新建
          </a-button>
        </template>
        <a-table
          :columns="shiftColumns"
          :data-source="doctorShiftTableData"
          :pagination="pagination"
          :loading="loading2"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'shiftType'">
              <a-tag color="#2db7f5" v-if="record.shiftType === 1">全日</a-tag>
              <a-tag color="#88e8db" v-if="record.shiftType === 2">半日</a-tag>
            </template>
            <template v-if="column.dataIndex === 'status'">
              <!-- 已過期：紅色（警告/失效） -->
              <a-tag
                color="red"
                v-if="record.endDate && record.endDate < nowDate"
                >已過期</a-tag
              >
              <!-- 未生效：灰色（未激活） -->
              <a-tag color="gray" v-else-if="record.startDate > nowDate"
                >待生效</a-tag
              >
              <!-- 生效中：綠色（成功/有效） -->
              <a-tag color="green" v-else>生效中</a-tag>
            </template>
            <template v-if="column.dataIndex === 'updatedAt'">
              {{ $formatDate(record.updatedAt) }}
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button
                  type="primary"
                  size="small"
                  @click="handleEdit(record)"
                  v-if="record.endDate > nowDate || record.endDate == null"
                  >編輯</a-button
                >
                <a-button
                  danger
                  size="small"
                  @click="handleDelete(record)"
                  v-if="record.startDate > nowDate"
                  >刪除</a-button
                >
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>

      <!-- 操作按鈕 -->
      <BackButton />

      <a-modal
        v-model:open="showModalCreate"
        title="新建駐診形式記錄"
        :footer="null"
      >
        <DynamicForm
          ref="createFormRef"
          :fieldConfig="createFieldConfig"
          @submit="handleCreateSubmit"
        />
      </a-modal>

      <!-- 修改模態框 -->
      <a-modal v-model:open="showModalEdit" :footer="null">
        <template #title>
          編輯駐診形式記錄
          <a-tag color="warning"
            ><template #icon>
              <ExclamationCircleOutlined />
            </template>
            ID: {{ editFormData.id }}</a-tag
          >
        </template>
        <DynamicForm
          ref="editFormRef"
          :fieldConfig="editFieldConfig"
          @submit="handleEditSubmit"
          :formData="editFormData"
        />
      </a-modal>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import { doctorApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import BackButton from "@/components/BackButton.vue";
import {
  tableColumns,
  getCreteFieldConfig,
  getEditFieldConfig,
} from "@/models/doctorShift";
import { createPagination } from "@/utils/pagination";
import { message, Modal } from "ant-design-vue";
import DynamicForm from "@/components/DynamicForm.vue";

const route = useRoute();
const nowDate = new Date().toISOString().slice(0, 10);

// 麵包屑導航
const breadcrumbItems = [
  { url: "/doctor", name: "醫師列表" },
  { url: "", name: "醫師詳情" },
];

// 消息詳情數據
const doctorDetail = ref<any>({});
const loading1 = ref(true);
const rightArr = ref<any>({});

// 獲取消息詳情
const fetchdoctorDetail = async () => {
  try {
    loading1.value = true;
    const { data } = await doctorApi.getDoctorDetail(Number(route.params.id));
    doctorDetail.value = data;
    rightArr.value = [
      {
        lable: "診金分成",
        key: "hasConsultShare",
        can: doctorDetail.value.right?.hasConsultShare,
      },
      {
        lable: "附加項目分成",
        key: "hasAdditionalShare",
        can: doctorDetail.value.right?.hasAdditionalShare,
      },
      {
        lable: "常規銷售分成",
        key: "hasRegularShare",
        can: doctorDetail.value.right?.hasRegularShare,
      },
      {
        lable: "附加推廣分成",
        key: "hasExtraShare",
        can: doctorDetail.value.right?.hasExtraShare,
      },
      {
        lable: "獎金分成",
        key: "hasBonus",
        can: doctorDetail.value.right?.hasBonus,
      },
      {
        lable: "查看分成記錄",
        key: "viewShareRecord",
        can: doctorDetail.value.right?.viewShareRecord,
      },
    ];
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    loading1.value = false;
  }
};

// 駐診形式記錄列表
const pagination = createPagination({ useRoute: false });
const shiftColumns = tableColumns;
const doctorShiftTableData = ref([]);
const loading2 = ref(true);

const fetchDoctorShifts = async (params?: {
  page: number;
  pageSize: number;
}) => {
  try {
    loading2.value = true;
    const {
      data: { list, page, limit, total },
    } = await doctorApi.getDoctorShiftRecordList(Number(route.params.id), {
      ...params,
      pageSize: 5,
    });
    doctorShiftTableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取駐診形式記錄列表失敗", error);
  } finally {
    loading2.value = false;
  }
};

const handleTableChange = (pagination: any) => {
  fetchDoctorShifts({
    page: pagination.current,
    pageSize: pagination.pageSize,
  });
};

// 新建
const createFieldConfig = ref<Record<string, any>>({});
const showModalCreate = ref(false);
const handleCreate = () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreteFieldConfig();
  }
  showModalCreate.value = true;
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    await doctorApi.createDoctorShift(Number(route.params.id), data);
    message.success("創建駐診形式記錄成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchDoctorShifts();
  } catch (error) {
    console.error("創建駐診形式記錄失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 編輯
const editFieldConfig = ref<Record<string, any>>({});
const editRecordId = ref(0);
const editFormData = reactive<any>({});

const showModalEdit = ref(false);
const handleEdit = (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, record);
  showModalEdit.value = true;
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await doctorApi.updateDoctorShift(
      Number(route.params.id),
      editRecordId.value,
      data
    );
    message.success("修改駐診形式記錄成功");
    showModalEdit.value = false;
    fetchDoctorShifts();
  } catch (error) {
    console.error("修改駐診形式記錄失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 刪除
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除駐診形式記錄 ${record.id} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await doctorApi.deleteDoctorShift(Number(route.params.id), record.id);
        message.success("刪除駐診形式記錄成功");
        fetchDoctorShifts();
      } catch (error) {
        console.error("刪除駐診形式記錄失敗:", error);
      }
    },
  });
};

// 初始化加載
onMounted(() => {
  fetchdoctorDetail();
  fetchDoctorShifts();
});
</script>

<style scoped></style>
